﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PerfumeShopManagement.Model;
using PerfumeShopManagement.Utility;

namespace PerfumeShopManagement.Controller
{
    public class AccountController : AbstractBaseController
    {
        public override object GetObjectById(object id)
        {
            string username = (string)id;
            var result = (from u in _context.Users
                          where u.Username.Equals(username)
                          select u).FirstOrDefault();
            return result;
        }

        public override List<object> GetAllObjects()
        {
            throw new NotImplementedException();
        }

        public override List<object> GetObjectsByCriteria(object obj)
        {
            User user = (User)obj;

            var usersQuery = (from u in _context.Users
                              select u);

            if (user.RoleId != 0)
                usersQuery = usersQuery.Where(u => u.RoleId.Equals(user.RoleId));

            if (!StringUtil.isEmptyOrBlank(user.Username))
                usersQuery = usersQuery.Where(u => u.Username.Contains(user.Username));
   
            if (!StringUtil.isEmptyOrBlank(user.Password))
                usersQuery = usersQuery.Where(u => u.Password.Contains(user.Password));

            if (usersQuery != null)
                return usersQuery.ToList<object>();

            return new List<object>();
        }

        public override bool Save(object obj)
        {
            User user = (User)obj;
            if (_context.Users.Contains(user)) // Update
            {
                User userRow = _context.Users.Single(
                    u => u.Username == user.Username);
                userRow.Password = user.Password;
                userRow.RoleId = user.RoleId;
                _context.SubmitChanges();
            }
            else // Insert
            {
                _context.Users.InsertOnSubmit(user);
                _context.SubmitChanges();
            }

            return true;
        }

        public override bool Delete(object obj)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteById(object id)
        {
            bool deleted = false;
            int userId = (int)id;
            var result = (from u in _context.Users
                          where u.Username.Equals(userId)
                          select u).FirstOrDefault();
            if (result != null)
            {
                _context.Users.DeleteOnSubmit((User)result);
                _context.SubmitChanges();
                deleted = true;
            }

            return deleted;
        }
    }
}
